package com.xuecheng.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.api.system.model.dto.CourseCategoryDTO;
import com.xuecheng.api.system.model.dto.CourseCategoryOperDTO;
import com.xuecheng.common.domain.code.CommonErrorCode;
import com.xuecheng.common.domain.response.RestResponse;
import com.xuecheng.common.util.StringUtil;
import com.xuecheng.system.convert.CourseCategoryConvert;
import com.xuecheng.system.entity.CourseCategory;
import com.xuecheng.system.entity.ext.CourseCategoryNode;
import com.xuecheng.system.mapper.CourseCategoryMapper;
import com.xuecheng.system.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {



    public List<CourseCategoryDTO> queryTreeNodes() {

        // 如何在mp对service封装中来获得mapper自定义的方法
        // mp中的service层封装里有个方法可以获得mapper的代理对象：getBaseMapper
        CourseCategoryMapper baseMapper = this.getBaseMapper();

        List<CourseCategoryNode> courseCategoryNodes = baseMapper.selectTreeNodes();

        List<CourseCategoryDTO> dtos = CourseCategoryConvert.INSTANCE.nodes2dtos(courseCategoryNodes);

        return dtos;
    }


    @Override
    public RestResponse< List<CourseCategory>> queryParentLists() {
        // 1.查询数据
        LambdaQueryWrapper<CourseCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseCategory::getParentid, "1");
        queryWrapper.eq(CourseCategory::getIsShow,1);
        queryWrapper.eq(CourseCategory::getIsLeaf, 0);

        List<CourseCategory> courseCategoryList = this.list(queryWrapper);

        // 2.判断查询后的数据
        if (ObjectUtils.isEmpty(courseCategoryList)) {
            return RestResponse.validfail("课程分类不存在");
        }

        return RestResponse.success(courseCategoryList);

    }

    @Override
    public RestResponse add(CourseCategoryDTO categoryDTO) {
        //1 dto -> entity
        CourseCategory courseCategory = CourseCategoryConvert.INSTANCE.dto2entity(categoryDTO);
        //2 参数校验
        String parentid = courseCategory.getParentid();
        if (StringUtil.isBlank(parentid) ){
            courseCategory.setIsLeaf(1);
            courseCategory.setParentid("1");
        }else {
            courseCategory.setIsLeaf(0);
        }
        //3 执行修改操作
        boolean b = this.save(courseCategory);
        //4 返回结果
        return b?RestResponse.success("新增成功"): RestResponse.validfail("新增失败");
    }

    @Override
    public RestResponse moveTo(CourseCategoryOperDTO categoryOperDTO) {
        // 1 根据id查询课程分类
        CourseCategory courseCategory = this.getById(categoryOperDTO.getId());
        if (courseCategory == null) {
            return RestResponse.validfail("课程分类不存在");
        }
        // 2 判断操作类型
        String operatType = categoryOperDTO.getOperatType();
        //2.1 上移操作
        LambdaQueryWrapper<CourseCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseCategory::getIsShow, 1);
        wrapper.eq(CourseCategory::getParentid, courseCategory.getParentid());
        wrapper.eq(CourseCategory::getIsLeaf,1);
        CourseCategory courseCategory1 = null;
        if ("UP".equals(operatType)) {
            // 查询当前记录的上一条记录
            wrapper.lt(CourseCategory::getOrderby, courseCategory.getOrderby());
            wrapper.orderByDesc(CourseCategory::getOrderby);
            Page<CourseCategory> page = this.page(new Page<>(0,1), wrapper);
            List<CourseCategory> records = page.getRecords();
            //获取上一条记录
            if (records == null || records.size() <= 0) {
                return RestResponse.validfail("顶部分类不能上移");
            }
            courseCategory1 = records.get(0);
            // 交换sort
            int sort = courseCategory.getOrderby();
            courseCategory.setOrderby(courseCategory1.getOrderby());
            courseCategory1.setOrderby(sort);
        } else {
            //2.2 下移操作
            // 查询当前记录的下一条记录
            wrapper.gt(CourseCategory::getOrderby, courseCategory.getOrderby());
            wrapper.orderByAsc(CourseCategory::getOrderby);
            Page<CourseCategory> page = this.page(new Page<>(0,1), wrapper);
            List<CourseCategory> records = page.getRecords();
            if (records == null || records.size() <= 0) {
                return RestResponse.validfail("底部分类不能下移");
            }
            //获取下一条记录
            courseCategory1 = records.get(0);
            // 交换sort
            int sort = courseCategory.getOrderby();
            courseCategory.setOrderby(courseCategory1.getOrderby());
            courseCategory1.setOrderby(sort);
        }
        //3 更新数据库
        boolean b = this.updateById(courseCategory);
        boolean b1 = this.updateById(courseCategory1);
        //4 返回执行结果
        return (b && b1) ? RestResponse.success("更新成功") : RestResponse.validfail("更新失败");
    }

    @Override
    public RestResponse delete(String courseCategoryId) {
        // 1 根据id查询课程分类
        CourseCategory courseCategory = this.getById(courseCategoryId);
        if (courseCategory == null) {
            return RestResponse.validfail("课程分类不存在");
        }
        // 2 如果删除的是 父分类,需要先判断当前分类下是否有子分类,如果有则不允许删除
        LambdaQueryWrapper<CourseCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseCategory::getParentid, courseCategoryId);
        wrapper.eq(CourseCategory::getIsShow,1);
        int count = this.count(wrapper);
        if (count > 0) {
            return RestResponse.validfail("课程分类下存在子分类不允许删除");
        }
        //3 执行删除
        boolean b = this.removeById(courseCategoryId);

        //4 返回执行结果
        return b?RestResponse.success("删除成功"): RestResponse.validfail("删除失败");
    }

    @Override
    public RestResponse edit(CourseCategoryDTO categoryDTO) {
        //1 dto -> entity
        CourseCategory courseCategory = CourseCategoryConvert.INSTANCE.dto2entity(categoryDTO);
        //2 参数校验
        if (StringUtil.isBlank(courseCategory.getId())){
            return RestResponse.validfail("课程分类ID不存在");
        }
        String parentid = courseCategory.getParentid();
        if (StringUtil.isNotBlank(parentid) && "1".equals(parentid) ){
            courseCategory.setIsLeaf(0);
        }else {
            courseCategory.setIsLeaf(1);
        }
        //3 执行修改操作
        boolean b = this.updateById(courseCategory);
        //4 返回结果
        return b?RestResponse.success("更新成功"): RestResponse.validfail("更新失败");
    }


    public RestResponse<CourseCategoryDTO> getCourseCategoryById4s(String id) {

        // 1.判断关键数据
        if (StringUtil.isBlank(id)) {
            return RestResponse.validfail(CommonErrorCode.E_100101);
        }

        // 2.根据id查询数据
        CourseCategory courseCategory = this.getById(id);

        // 3.判断查询后的数据
        if (ObjectUtils.isEmpty(courseCategory)) {
            return RestResponse.validfail("课程分类不存在");
        } else {

            CourseCategoryDTO dto = CourseCategoryConvert.INSTANCE.entity2dto(courseCategory);

            return RestResponse.success(dto);
        }

    }
}
